package com.school.information.core.service;

import com.school.information.core.exception.ServiceException;
import com.school.information.core.security.entity.SecurityUser;
import com.school.information.entity.SysUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.enums.status.EnabledEnum;
import com.school.information.service.SysMenuService;
import com.school.information.service.SysRoleService;
import com.school.information.service.SysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Set;

@Service
@Slf4j
public class SecurityUserServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService menuService;
    @Resource
    private SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("##进入后台用户登录逻辑代码处理：{}", username);
        // 根据登录名获取用户信息
        SysUserEntity sysUser = sysUserService.getByPhone(username);
        if (Objects.isNull(sysUser)) {
            log.error("##登录用户：{}不存在", username);
            throw new ServiceException(SysResultEnum.USER_NAME_NO_EXISTED);
        } else if (EnabledEnum.DISABLE.equals(sysUser.getIsEnabled())) {
            log.error("##登录用户：{}已停用", username);
            throw new ServiceException(SysResultEnum.USER_DISABLED);
        }
        // 获取用户角色、权限信息  用户角色和权限信息保留一个即可
        SecurityUser securityUser = new SecurityUser();
        securityUser.setSysUser(sysUser);

        Set<String> perms = menuService.findMenuByUserId(sysUser.getId());
        securityUser.setPermissions(perms);

        Set<String> roles = roleService.findRoleByUserId(sysUser.getId());
        securityUser.setRoles(roles);

        return securityUser;
    }
}
